#!/usr/bin/env python
# -*- coding: utf-8 -*

import _curses, curses,curses.ascii,types

class PyPad:
    class PyPadLine:
	def __init__(self,line,collapsed=0,collaps=0):
	    self.line = line.replace("\n","")
	    self.collapsed = collapsed
	    self.collaps = collaps

    def __init__(self,screen,lines=[],dx={"x":0,"y":0},size={"width":0,"height":0}):
	self.lines = []
	self.dx = dx
	self.size = size
	self.screen = screen
	self.page = {"top":0,"left":0}

	for line in lines:
	    self.lines+=[PyPad.PyPadLine(line)]
	    
	    
    def clearline(self,y):
	self.screen.addstr(y+self.dx["y"],self.dx["x"], "".join([" " for i in range(self.size["width"])]) )
	
    def drawline(self,y):
        if (y+self.page["top"])<len(self.lines):
	    self.screen.addstr(y+self.dx["y"],self.dx["x"], self.lines[y+self.page["top"]].line[0:self.size["width"]])
		
	
    def build(self):
	self.screen.clear()
	for y in range(0,self.size["height"]):
	    self.drawline(y)
		
	
    def insert(self,line,x,y):
	if (x> len( unicode( self.lines[y+self.page["top"] ].line, "UTF-8",errors="ignore") )-1):
	    tmp = self.lines[y+self.page["top"]].line + line
	else:
	    tmp = self.lines[y+self.page["top"]].line
	    tmp = tmp[:x] + line + tmp[x:]
	#self.lines[y].line[:x] + line + self.lines[y].line[x+1:] 
	#self.lines[y].line[x:x] = line
	self.lines[y+self.page["top"]].line = tmp
	self.clearline(y)
	self.drawline(y)
	return len(unicode(line,"UTF-8",errors="ignore")) 


    def bs(self,x,y):
	line = unicode(self.lines[y+self.page["top"]].line,"UTF-8",errors="ignore")
	
	line = line[:x-1]+line[x:]
	self.lines[y+self.page["top"]].line = line.encode("UTF-8","ignore")
	self.clearline(y)
	self.drawline(y)
	return -1


    def delete(self,x,y):
	line = unicode(self.lines[y+self.page["top"]].line,"UTF-8",errors="ignore")
	cnt = len(line[:x].split("\t"))-1
	line = line[:x]+line[x+1:]
		
	
	self.lines[y+self.page["top"]].line = line.encode("UTF-8","ignore")
	self.clearline(y)
	self.drawline(y)
	return 0


    def pageup(self):
	self.page["top"] -= self.size["height"]
	if (self.page["top"]<0):self.page["top"]=0
	self.build() 	

    def pagedown(self):
	self.page["top"] += self.size["height"]
	if (self.page["top"]+self.size["height"]>len(self.lines) ):self.page["top"]=len(self.lines-self.size["height"])
	self.build() 	

	
    def set_cursor(self,x,y):
	if (x<0):x=0
	if (y<0):
	    y=0
	    if (self.page["top"]>0): 
		self.page["top"]-=1
		self.build();
		
		
	if (x>self.size["width"]-1): x=self.size["width"]-1
	
	if (y>self.size["height"]-1): 
	    y=self.size["height"]-1
	    if (self.page["top"]<len(self.lines)):
		self.page["top"]+=1
		self.build() 
	
	
	if (x>len(self.lines[y+self.page["top"]].line)): x = len(self.lines[y+self.page["top"]].line)
	
	
	y,x = y+self.dx["y"] ,x+self.dx["x"]
	self.screen.move(y,x)
	return x-self.dx["x"],y-self.dx["y"]
	
	